<template>
	<view class="page">
		<!--		背景图片-->
		<image
			class="background-image"
			src="https://kou.gdzmtech.com/pic/c803300a-b35b-4e4a-8256-bb9b83ff3007.png"
			mode="widthFix"
		></image>
		<view class="invite-record" @click="viewShareRecord">
			邀请记录
			<image
				class="icon"
				src="/static/mine/right-arrow-2.png"
				mode="widthFix"
			></image>
		</view>
		<view class="footer-btn-container">
			<button open-type="share" class="wechat-share btn">微信分享</button>
			<view class="poster-share btn" @click="openPosterSelectPopup"
			>海报分享
			</view
			>
		</view>
		<uni-popup ref="popup" type="center">
			<view class="preview-image-container">
				<canvas canvas-id="shareImg" id="shareImg" class="shareImg"></canvas>
				<view class="save-btn" @click="saveQrCode" v-if="loading === false"
				>保存到相册
				</view
				>
			</view>
		</uni-popup>
		<!-- 选择海报类型弹框 -->
		<uni-popup ref="choosePosterPopup">
			<view class="choose-poster-container">
				<view class="title">请选择海报类型</view>
				<view
					class="poster-item"
					@click="generateSharePost(item)"
					v-for="item in posterList"
					:key="item.posterId"
				>{{ item.platformName }}
				</view
				>
			</view>
		</uni-popup>
	</view>
</template>
<script>
import store from "../../../store"
import request from "../../../utils/request"
import { getStaticUrl } from "../../../utils/settings"
import { getShowImage } from "@/utils"
import { userActionType } from "../../../store/modules/user"
import shareInfo from "../../../utils/shareInfo"

let ctx = null
let canvasWidth = 0
let canvasHeight = 0
export default {
	data() {
		return {
			loading: false,
			posterList: [],
		}
	},
	methods: {
		//获取分享海报列表
		async getSharePosterList() {
			uni.showLoading({
				title: "加载中",
				mask: true,
			})
			try {
				const userInfo = await store.dispatch(userActionType.action.userInfo)
				const res = await request({
					url: "userSharePoster/listSharePoster",
					method: "post",
					data: {
						userId: userInfo.id,
					},
				})
				console.log(res, "res")
				this.posterList = res
			} catch (e) {
				console.log(e, "error")
			} finally {
				uni.hideLoading()
			}
		},
		//查看邀请记录
		viewShareRecord() {
			uni.navigateTo({
				url: "/markingCampaign/pages/recommender/inviteRecord",
			})
		},
		//生成分享海报
		//type参数为生成的海报类型，1 专升本，2 普通话，3 四六级，4 刷题鱼平台
		generateSharePost(sharePosterItem) {
			this.$refs.choosePosterPopup.close()
			this.$refs.popup.open()
			this.$nextTick(async () => {
				//清理上一次的画布
				if (ctx) {
					ctx.clearRect(0, 0, canvasWidth, canvasHeight)
					ctx.draw()
				}
				uni.showLoading({
					title: "加载中",
					mask: true,
				})
				this.loading = true
				//加载小程序二维码
				const qrCodeImgUrlRow = await this.generateCode(sharePosterItem)
				const qrCodeImgUrl = await this.downloadImage(
					getStaticUrl() + qrCodeImgUrlRow,
				)
				//加载海报图片
				const postImgUrl = await this.downloadImage(
					getShowImage(sharePosterItem.platformPoster),
				)
				//合成
				this.drawPost(qrCodeImgUrl, postImgUrl)
				this.loading = false
				uni.hideLoading()
			})
		},
		//生成小程序二维码
		//type参数为生成的二维码类型，1 专升本，2 普通话，3 四六级，4 刷题鱼平台
		// env_version: "trial" 体验版; "release" 正式版; "develop" 开发版
		async generateCode(item) {
			try {
				const userInfo = await store.dispatch(userActionType.action.userInfo)
				const id = userInfo.id
				const res = await request({
					url: "userSharePoster/generateShareQRCode",
					method: "post",
					data: {
						scene: "TJG" + id,
						// env_version: "trial",
						env_version: "release",
						width: 300,
						shareClass: item.platformCode,
					},
				})
				return res.url
			} catch (err) {
				console.log(err, "err")
				uni.showToast({
					title: err,
					icon: "none",
					duration: 2000,
				})
			}
		},
		// 下载图片
		downloadImage(url, success) {
			return new Promise((resolve, reject) => {
				uni.downloadFile({
					url: url,
					success: (res) => {
						resolve(res.tempFilePath)
					},
					fail: (err) => {
						this.showPost = false
						console.log(err, "err")
						uni.showToast({
							title: err,
							icon: "none",
							duration: 2000,
						})
						reject()
					},
				})
			})
		},
		// 绘制海报
		drawPost(qrCodeImgUrl, postImgUrl) {
			var query = uni.createSelectorQuery()
			query.select("#shareImg").boundingClientRect()
			query.exec((res) => {
				// 画布宽高
				canvasWidth = res[0].width
				canvasHeight = res[0].height
				ctx = uni.createCanvasContext("shareImg") // 画笔
				ctx.beginPath()
				// 绘制海报图片
				ctx.drawImage(postImgUrl, 0, 0, canvasWidth, canvasHeight)
				// 绘制小程序码
				ctx.drawImage(
					qrCodeImgUrl,
					canvasWidth * 0.75,
					canvasHeight * 0.81,
					canvasWidth * 0.22,
					canvasWidth * 0.22,
				)
				ctx.closePath()
				ctx.draw()
			})
		},
		// 保存到相册
		saveQrCode() {
			uni.canvasToTempFilePath({
				x: 0,
				y: 0,
				width: 1080,
				height: 1440,
				destWidth: 1080 * 3,
				destHeight: 1440 * 3,
				canvasId: "shareImg",
				success: (res) => {
					uni.saveImageToPhotosAlbum({
						filePath: res.tempFilePath,
						success: () => {
							uni.showToast({
								title: "保存成功",
								icon: "success",
								mask: true,
							})
						},
						
						fail: (err) => {
							uni.showModal({
								title: "提示",
								content: "需要您授权保存相册",
								showCancel: false,
								success: (res) => {
									if (res.confirm) {
										uni.openSetting({
											success: (settingdata) => {
												if (settingdata.authSetting["scope.writePhotosAlbum"]) {
													uni.showToast("获取权限成功,再次保存图片即可成功")
												} else {
													uni.showToast("获取权限失败，将无法保存到相册")
												}
											},
										})
									}
								},
							})
							console.log(err)
						},
					})
				},
				fail: (err) => {
					console.log(err, "???")
					uni.showToast({
						title: "保存失败",
						icon: "none",
						mask: true,
					})
				},
			})
		},
		//打开分享海报选择弹框
		async openPosterSelectPopup() {
			await this.getSharePosterList()
			this.$refs.choosePosterPopup.open()
		},
	},
	onShareAppMessage: async () => {
		return await shareInfo.getDefaultShareInfo()
	},
}
</script>
<style lang="scss" scoped>
.page {
	position: relative;
	//height: 2372rpx;
	//background: url("https://kou.gdzmtech.com/pic/c803300a-b35b-4e4a-8256-bb9b83ff3007.png");
	//background-size: 100% 100%;
	.background-image {
		width: 100vw;
		position: absolute;
		top: 0;
		left: 0;
	}
	
	.invite-record {
		position: absolute;
		right: 28rpx;
		top: 24rpx;
		background: rgba(0, 0, 0, 0.4);
		border-radius: 34rpx 34rpx 34rpx 34rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		color: white;
		width: 172rpx;
		height: 60rpx;
		font-size: 28rpx;
		
		.icon {
			margin-left: 8rpx;
			width: 11rpx;
		}
	}
	
	.footer-btn-container {
		position: fixed;
		bottom: 92rpx;
		right: 0;
		width: 100vw;
		display: flex;
		justify-content: space-around;
		
		.wechat-share {
			background-color: white;
			color: #333333;
			margin: 0 !important;
		}
		
		.poster-share {
			background: linear-gradient(270deg, #ddc087 0%, #ebd0b6 100%);
			color: #5a4531;
		}
		
		.btn {
			width: 320rpx;
			height: 92rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 36rpx;
			font-weight: 600;
			border-radius: 46rpx;
		}
	}
	
	.preview-image-container {
		.shareImg {
			width: 540rpx;
			height: 720rpx;
		}
		
		.save-btn {
			margin-top: 40rpx;
			margin-left: auto;
			margin-right: auto;
			width: 320rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 80rpx;
			background-color: white;
			border-radius: 40rpx;
		}
	}
}

.choose-poster-container {
	background: white;
	border-radius: 20rpx;
	padding: 80rpx 0;
	
	.title {
		font-size: 36rpx;
		font-weight: 600;
		color: #333333;
		margin-bottom: 40rpx;
		padding: 0 80rpx;
	}
	
	.poster-item {
		font-size: 32rpx;
		color: #333333;
		padding: 40rpx 80rpx;
		text-align: center;
		border-bottom: 1px solid #dbdbdb;
		
		&:active {
			background: #f5f5f5;
		}
	}
}
</style>
